<template>
  <!-- 新增/修改用户按钮dialog -->
  <Edialog
    :outershow="institutionShow"
    :title="userTitle"
    saveClick
    @close="closeFn()"
    @saveFn="saveFn()"
  >
    <div style="padding: 0 20px">
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        :rules="institutionRules"
      >
        <el-form-item label="用户名" prop="memberUsername">
          <el-input
            v-model="form.memberUsername"
            placeholder="请输入用户编号（1-20）"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="memberNickname">
          <el-input
            v-model="form.memberNickname"
            placeholder="请输入昵称（1-100）"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="memberPassword"
          v-if="userTitle == '新增'"
        >
          <div class="da">
            <el-input
              v-model="form.memberPassword"
              placeholder="请输入密码"
            ></el-input>
            <el-tooltip effect="dark" placement="top">
              <div slot="content">
                1、不能包含用户名(大小写都不允许),例如某用户的用户名是yy,那么以下字符都不允许例如Yy,YY,yy<br />
                2、不能使用3个及以上连续顺序数字序列,例如123,234,012都不允许,014允许<br />
                3、不能使用3个及以上连续倒序数字序列,例如321,432,210都不允许,421允许<br />
                4、不能使用3个及以上连续顺序字符(大小写都不允许),例如abc,Abc,ABC都不允许,abd允许<br />
                5、不能使用3个及以上连续倒序字符(大小写都不允许),例如cba,Cba,CBA都不允许,dba允许<br />
                6、不能使用3个及以上连续相同数字、字母(大小写都不允许)、或者字符,例如aaa,aAa,AAA,777,$$$都不允许,aab允许<br />
                7、密码位数要大于8位，不能包含用户名，至少包含以下四类字符中的三类字符:
                a、英文大写字母(A到Z) b、英文小写字母(a到z)
                c、10个基本数字(0到9) d、非字母字符(例如!、$、#、%)
              </div>
              <i
                class="el-icon-question"
                style="color: #ccc; font-size: 22px; cursor: pointer"
              ></i>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="用户电话">
          <el-input
            v-model="form.memberPhone"
            placeholder="请输入用户电话（1-20）"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户备注">
          <el-input
            v-model="form.memberDesc"
            placeholder="请输入用户备注（1-200）"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属机构" prop="institution">
          <el-input
            v-model="form.institution"
            disabled
            placeholder="点击右侧选择"
          ></el-input>
          <span class="show-pwd" @click="showTree(1)">
            <svg-icon icon-class="tree" />
          </span>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-input
            v-model="department"
            disabled
            placeholder="点击右侧选择"
          ></el-input>
          <span class="show-pwd" @click="showTree">
            <svg-icon icon-class="tree" />
          </span>
        </el-form-item>
      </el-form>
    </div>
    <!-- 内部dialog -->
    <el-dialog
      width="30%"
      class="innerBox"
      :title="selectTitle"
      :visible.sync="innerVisible"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-tree
        :data="treeData"
        default-expand-all
        :props="treeDefaultProps"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node" slot-scope="{ data }">
          <i
            v-if="data.ab.type == 1"
            class="el-icon-office-building"
            style="margin-right: 10px"
          ></i>
          <i
            v-if="data.ab.type == 2"
            class="el-icon-house"
            style="margin-right: 10px"
          ></i>
          <span>{{ data.name }}</span>
        </span>
      </el-tree>
    </el-dialog>
  </Edialog>
</template>

<script>
import Edialog from "@/components/Edialog";
import {
  getSysMemberId,
  putSysMember,
  postcheckPasswordRule,
  getSysOrgDepartCurrTree,
  postSysMember,
} from "@/api/management/user";
import { fd, systemCode, generateRandom } from "@/utils";
export default {
  components: {
    Edialog,
  },
  data() {
    return {
      institutionShow: false,
      form: {
        memberNickname: "",
        memberPassword: "",
        memberUsername: "",
        memberPhone: "",
        memberDesc: "",
        institution: "",
      },
      // 表单校验
      institutionRules: {
        memberNickname: [
          {
            required: true,
            message: "请输入昵称（1-100）",
            trigger: "blur",
          },
          { min: 1, max: 100, message: "请输入1-100位", trigger: "blur" },
        ],
        memberUsername: [
          { required: true, message: "请输入用户名（1-20）", trigger: "blur" },
          { min: 1, max: 20, message: "请输入1-20位", trigger: "blur" },
        ],
        institution: [
          { required: true, message: "请选择所属机构", trigger: "blur" },
        ],
        memberPassword: [
          {
            required: true,
            message: "请输入大于8位，由英文、数字、特殊字符组成的密码",
            trigger: "blur",
          },
          {
            min: 8,
            max: 100,
            message: "请输入大于8位，由英文、数字、特殊字符组成的密码",
            trigger: "blur",
          },
        ],
      },
      userTitle: "",

      // --------------------- 内嵌 ---------------------
      department: "",
      selectTitle: "",
      innerVisible: false,
      treeData: [],
      treeDefaultProps: {
        children: "children",
        label: "name",
      },
      selectOne: "",
      selectTwo: "",
      // 存放展示的树
      alltree: [],
      // 保存机构部门的平级数据
      allData: [],
      departId: "",
      orgId: "",
    };
  },
  methods: {
    async open(scope) {
      // 新增
      if (!scope) {
        this.userTitle = "新增";
        this.department =
          (this.$store.state.user.userInfo.orgDepart &&
            this.$store.state.user.userInfo.orgDepart.departName) ||
          "";
        this.form.institution =
          (this.$store.state.user.userInfo.org &&
            this.$store.state.user.userInfo.org.orgName) ||
          "";
        this.selectOne =
          (this.$store.state.user.userInfo.org &&
            this.$store.state.user.userInfo.org.id) ||
          "";
        this.selectTwo =
          (this.$store.state.user.userInfo.orgDepart &&
            this.$store.state.user.userInfo.orgDepart.id) ||
          "";
        this.form.memberPassword =
          generateRandom(4) + "@" + generateRandom(4, "digit");
        this.institutionShow = true;
        return;
      }
      // 修改
      this.userTitle = "修改";
      this.clickUserId = scope.ID;
      let res = await getSysMemberId(scope.ID);
      console.log("修改用户", res);
      this.form.memberNickname = res.data.bdata.memberNickname;
      this.form.memberUsername = res.data.bdata.memberUsername;
      this.form.memberPhone =
        res.data.bdata.memberPhone === null ? "" : res.data.bdata.memberPhone;
      this.form.memberDesc =
        res.data.bdata.memberDesc === null ? "" : res.data.bdata.memberDesc;
      // 机构
      this.form.institution = res.data.bdata.orgName;
      this.department = res.data.bdata.departName;
      this.orgId = res.data.bdata.orgId;
      this.departId = res.data.bdata.departId;
      this.institutionShow = true;
    },
    async saveFn() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res;
          let obj = JSON.parse(JSON.stringify(this.form));
          if (this.userTitle == "新增") {
            // 校验密码复杂度
            let checkedRes = await postcheckPasswordRule(
              fd({
                password: this.form.memberPassword,
                username: this.form.memberUsername,
              })
            );
            if (checkedRes.data && checkedRes.data.bcode == 0) {
              res = await putSysMember(
                fd({
                  ...obj,
                  orgId: this.selectOne,
                  departId: this.selectTwo,
                  systemCodeList: systemCode,
                })
              );
            } else {
              return;
            }
          } else {
            delete obj.memberPassword;
            res = await postSysMember(
              fd({
                ...obj,
                id: this.clickUserId,
                departId: this.selectTwo,
                orgId: this.selectOne ? this.selectOne : this.orgId,
                systemCodeList: systemCode,
              })
            );
          }
          if (res.code == 0 && res.data.bcode == 0) {
            this.$message.success("操作成功");
            this.closeFn();
            this.$emit("callBackFn");
            this.institutionShow = false;
          }
        }
      });
    },
    closeFn() {
      this.form.memberNickname = "";
      this.form.memberPassword = "";
      this.form.memberUsername = "";
      this.form.memberPhone = "";
      this.form.memberDesc = "";
      this.institutionShow = false;
      this.$refs.form.clearValidate();
    },

    // ------------------------------ 内嵌 ------------------------------
    async showTree(val) {
      this.alltree = [];
      this.treeData = [];
      let res = await getSysOrgDepartCurrTree();
      this.allData = res.data.bdata;
      res.data.bdata.forEach((item) => {
        let tim = res.data.bdata.some((i) => {
          if (item.id != i.id) {
            return item.pid == i.id;
          }
        });
        if (!tim) {
          this.alltree.push(item);
        }
      });
      this.alltree.forEach((item) => {
        item.children = this.twoTree(res.data.bdata, item.id);
      });
      this.treeData = this.alltree;
      if (val == 1) {
        this.selectTitle = "选择机构";
      } else {
        this.selectTitle = "选择部门";
      }
      this.innerVisible = true;
    },
    handleNodeClick(val) {
      console.log("val", val);
      // 选择的是机构
      if (val.ab.type == 1) {
        this.form.institution = val.name;
        this.department = "";
        this.selectOne = val.id;
        this.selectTwo = "";
      } else {
        // 选择的是部门
        this.department = val.name;
        this.selectTwo = val.id;
        let tim = this.allData.find((item) => item.id == val.pid);
        this.form.institution = tim.name;
        this.selectOne = tim.id;
      }
      console.log("机构：", this.selectOne, "部门：", this.selectTwo);
      this.innerVisible = false;
    },
    twoTree(arr, pid) {
      const list = [];
      arr.forEach((v) => {
        if (v.pid === pid && v.id != pid) {
          list.push(v);
          const children = this.arrayToTree(arr, v.id);
          if (children.length) v.children = children;
        }
      });
      return list;
    },
    arrayToTree(arr, pid) {
      const list = [];
      arr.forEach((v) => {
        if (v.pid === pid) {
          list.push(v);
          const children = this.arrayToTree(arr, v.id);
          if (children.length) v.children = children;
        }
      });
      return list;
    },
  },
};
</script>

<style scoped lang="scss">
.show-pwd {
  position: absolute;
  right: 10px;
  top: 0px;
  font-size: 16px;
  color: #889aa4;
  cursor: pointer;
  user-select: none;
}
</style>
